package com.xxl.rpc.sample.server.service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Foo {

    Lock lock=new ReentrantLock();
    Condition condition1=lock.newCondition();
    Condition condition2=lock.newCondition();
    Condition condition3=lock.newCondition();
     int num=1;
     CountDownLatch countDownLatch = new CountDownLatch(3);


     class Task1 implements  Runnable{
        @Override
        public void run() {
            while (true){
                lock.lock();
                if(num!=1){
                    try {
                        condition1.await();// wait会释放锁 并且会阻塞
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("1");
                num=2;
                condition2.signal();
                lock.unlock();
            }
        }
    }
      class Task2 implements  Runnable{
        @Override
        public void run() {
            while (true){
                lock.lock();
                if(num!=2){
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("2");
                num=3;
                condition3.signal();
                lock.unlock();
            }
        }
    }
      class Task3 implements  Runnable{
        @Override
        public void run() {
            while(true){
                lock.lock();
                if(num!=3){
                    try {
                        condition3.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("3");
                num=1;
                condition1.signal();
                lock.unlock();
            }
        }
    }

    void doSumTask(){
        System.out.println("thread1");
        new Thread(new Task1()).start();
        System.out.println("thread3");
        new Thread(new Task3()).start();
        System.out.println("thread2");
        new Thread(new Task2()).start();

    }

    public static void main(String[] args) throws Exception{
        Foo foo = new Foo();
        foo.doSumTask();
    }
//https://leetcode-cn.com/problems/print-foobar-alternately/solution/chao-shi-de-tong-xue-zhu-yi-forxun-huan-epxsu/
}